const { isArrayBuffer } = require('util/types')
const ws = require('ws')

let messageType = {
  private: 'private',
  public: 'public',
  group: 'group'
}

let messageDataType = {
  text: 'text',
  audio: 'audio',
  video: 'videl'
}

let clients = new Map()

//文字聊天室
function startSocketService(httpServer) {

  console.log('startSocketService')
  const wss = new ws.Server({ server: httpServer })

  wss.on('connection', ws => {
    console.log('connect')

    ws.on('message', message => {
      console.log('message: ', message)

      let msg = ''
      if (isArrayBuffer(message)) {
        msg = ArrayBuffer.JSON.parse(message)
      }
      else {
        msg = typeof message === 'string' ? message : JSON.parse(message)
      }
      console.log('msg: ', msg)
      wss.clients.forEach(client => {
        // console.Console('client.send', client.send)
        client.send(message)
      })
    })

  })

  // const socketServer2 = new ws.Server({ server: httpServer })

  // socketServer2.on('connection', ws => {
  //   console.log('connect', ws)
  //   ws.on('message', message => {
  //     message = JSON.parse(message)
  //     wss.clients.send(message)
  //   })

  // })

  // console.log(`socketServer === socketServer2: ${socketServer === socketServer2}`)
}



module.exports = { startSocketService }